<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入账号关键词" clearable v-model="username" @clear="searchUser">
            <el-button slot="append" icon="el-icon-search" @click="searchUser"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>

      <el-table :data="userList" border stripe>
        <el-table-column label="ID" prop="id" :width="50"></el-table-column>
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="密码" prop="password"></el-table-column>
        <el-table-column label="昵称" prop="name"></el-table-column>
        <el-table-column label="头像">
          <template v-slot="scope">
            <el-image
                style="width: 100px; height: 100px"
                :src="'https://woniu-adopt.oss-cn-hangzhou.aliyuncs.com/adoptImages/'+scope.row.pic"
                fit="cover"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="性别">
          <template v-slot="scope">
            <span v-text="scope.row.gender === 0?'男':'女'"></span>
          </template>
        </el-table-column>
        <el-table-column label="手机号码" prop="telephone"></el-table-column>
        <el-table-column label="电子邮箱" prop="email"></el-table-column>
        <el-table-column label="详细地址" prop="address"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="状态">
          <template v-slot="scope">
            <span v-text="scope.row.locked === 0?'正常':'锁定'"></span>
          </template>
        </el-table-column>
        <el-table-column label="注册时间" prop="insertTime"></el-table-column>
        <el-table-column label="更新时间" prop="updateTime"></el-table-column>
        <el-table-column label="操作" :width="130">
          <template v-slot="scope">
            <el-button type="warning" size="small" icon="el-icon-edit" @click="showEditDialog(scope.row)"
                       circle></el-button>
            <span v-if="scope.row.locked === 0">
                <el-button type="primary" size="small" @click="changeLocked(scope.row.id)"
                           icon="el-icon-lock" circle></el-button>
              </span>
            <span v-if="scope.row.locked === 1">
                <el-button size="small" @click="changeLocked(scope.row.id)"
                           icon="el-icon-unlock" circle></el-button>
              </span>
            <el-button type="danger" size="small" icon="el-icon-delete"
                       @click="removeUserById(scope.row.id)" circle></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[6, 12 , 24]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>
    </el-card>
    <!--添加用戶-->
    <el-dialog title="添加用戶" :visible.sync="addDialogVisible" width="50%" :close-on-click-modal="false"
               @close="addUserFormClose">
      <el-form
          :model="addUserForm"
          :rules="addUserFormRules"
          ref="addUserFormRef"
          label-width="100px"
          class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username" @blur="judgedSameName(addUserForm.username)"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="name">
          <el-input v-model="addUserForm.name"></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="telephone">
          <el-input v-model="addUserForm.telephone"></el-input>
        </el-form-item>
        <el-form-item label="所在城市" prop="city">
          <!--省市级连-->
          <el-cascader
              size="large"
              :options="options"
              v-model="selectedOptions"
              @change="handleChange">
          </el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="addUserForm.address"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="addUserForm.gender" placeholder="请选择性别">
            <!--双引号内的值是绑定的值-->
            <el-option label="男" :value="0"></el-option>
            <el-option label="女" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="头像" prop="pic">
          <input type="file" @change="uploadPic"/>
          <img :src="showImg" alt="" :style="imgStyle"/>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="addUserForm.age"></el-input>
        </el-form-item>
        <!--锁定状态由操作处理，此处不处理-->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addUser">确 定</el-button>
        <el-button @click="addUserFormClose">取 消</el-button>
      </span>
    </el-dialog>

    <!--修改用戶-->
    <el-dialog
        title="修改用戶"
        :visible.sync="editDialogVisible"
        width="50%"
        :close-on-click-modal="false"
        @close="editUserFormClose"
    >
      <el-form
          :model="editUserForm"
          :rules="editUserFormRules"
          ref="editUserFormRef"
          label-width="100px"
          class="demo-ruleForm"
      >
        <el-form-item label="用户ID" prop="id">
          <el-input v-model="editUserForm.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="账户名" prop="username">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" type="password">
          <el-input v-model="editUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="name">
          <el-input v-model="editUserForm.name"></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="telephone">
          <el-input v-model="editUserForm.telephone"></el-input>
        </el-form-item>
        <el-form-item label="所在城市" prop="city">
          <!--省市级连-->
          <el-cascader
              size="large"
              :options="options"
              v-model="selectedOptions"
              @change="handleChange">
          </el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="editUserForm.address"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="editUserForm.gender" placeholder="请选择性别">
            <!----value需要绑定----->
            <el-option label="男" :value="0"></el-option>
            <el-option label="女" :value="1"></el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="头像" prop="pic">
          <input type="file" @change="uploadPic"/>
          <img :src="showImg" alt="" :style="imgStyle"/>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="editUserForm.age"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editUser">确 定</el-button>
        <el-button @click="editDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
//Element UI 中国省市区级联数据插件
//CodeToText是个大对象，属性是区域码，属性值是汉字 用法例如：CodeToText['110000']输出北京市
//github地址：https://github.com/Plortinus/element-china-area-data
import {regionData} from 'element-china-area-data';
import {CodeToText, TextToCode} from "element-china-area-data/dist/app";
import qs from "qs";

export default {
  data() {
    return {
      imgStyle: 'width:100px',
      showImg: 'https://woniu-adopt.oss-cn-hangzhou.aliyuncs.com/adoptImages/',
      options: regionData,
      //给添加的对话框中的城市一个默认值
      selectedOptions: ["110000", "110100", "110101"],
      city: '北京市市辖区东城区',
      flag: true,
      flag2: false,
      editDialogVisible: false,
      pageNum: 1,
      pageSize: 6,
      userList: [],
      total: 9,
      username: "",
      addDialogVisible: false,
      addUserForm: {
        username: "",
        password: "",
        name: "",
        address: "",
        telephone: "",
        email: "",
        city: [],
        gender: 0,
        pic: "",
        age: ""
      },
      editUserForm: {
        id: "",
        username: "",
        password: "",
        name: "",
        telephone: "",
        city: [],
        address: '',
        email: "",
        gender: 0,
        pic: "",
        age: ""
      },
      editUserFormRules: {
        password: [
          {required: true, message: "请输入密码", trigger: "blur"},
          {pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/, message: "密码至少包含 数字和英文，长度6-20", trigger: "blur"},
        ],
        name: [
          {required: true, message: "请输入昵称", trigger: "blur"},
          {pattern: /^[\u4E00-\u9FA5A-Za-z0-9_]{2,10}$/, message: "昵称由中文字母或数字组成，长度2~10位", trigger: "blur"}
        ],
        telephone: [
          {required: true, message: "请输入手机号", trigger: "blur"},
          {
            pattern: /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/,
            message: "手机号码不符合规则！",
            trigger: "blur"
          }
        ],
        address: [
          {required: true, message: "请输入地址", trigger: "blur"},
        ],
        email: [
          {required: true, message: "请输入邮箱账号", trigger: "blur"},
          {pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: "邮箱账号不符合规则！", trigger: "blur"}
        ],
        pic: [
          {required: true, message: "请选择头像", trigger: "blur"},
        ],
        age: [{required: true, message: "请输入年龄", trigger: "blur"},
          {pattern: /^[1-99]*$/, message: "年龄1~99！", trigger: "blur"}]
      },
      addUserFormRules: {
        username: [
          {
            validator: (rule, value, callback) => {
              let reg = /^[\u4e00-\u9fa5_a-zA-Z0-9.·-]+$/;
              if (!value) {
                callback(new Error('用户名为必填项'));
              } else if (value.length < 4 || value.length > 10) {
                callback(new Error('长度在 4 到 10 个字符'));
              } else if (!reg.test(value)) {
                callback(new Error('用户名不支持特殊字符'));
              } else if (this.flag2) {
                callback(new Error('用户名已存在'));
              } else {
                callback();
              }
            }
            , trigger: 'blur'
          },
        ],
        password: [
          {required: true, message: "请输入密码", trigger: "blur"},
          {pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/, message: "密码至少包含 数字和英文，长度6-20", trigger: "blur"},
        ],
        name: [
          {required: true, message: "请输入昵称", trigger: "blur"},
          {pattern: /^[\u4E00-\u9FA5A-Za-z0-9_]{2,10}$/, message: "昵称由中文字母或数字组成，长度2~10位", trigger: "blur"}
        ],
        telephone: [
          {required: true, message: "请输入手机号", trigger: "blur"},
          {
            pattern: /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/,
            message: "手机号码不符合规则！",
            trigger: "blur"
          }
        ],
        address: [
          {required: true, message: "请输入地址", trigger: "blur"},
        ],
        email: [
          {required: true, message: "请输入邮箱账号", trigger: "blur"},
          {pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: "邮箱账号不符合规则！", trigger: "blur"}
        ],
        /*pic: [
          {required: true, message: "请选择头像", trigger: "blur"},
        ],*/
        age: [{required: true, message: "请输入年龄", trigger: "blur"},
          {pattern: /^[1-99]*$/, message: "年龄1~99！", trigger: "blur"}]
      }
    };
  },
  methods: {
    judgedSameName(username){
      let url='/user/judgedSameName';
      console.log(username)
      this.$axios.get(url,{
        params: {userName:username}
      }).then(res=>{
        if(res.data.code===201){
          console.log(res.data.msg);
          this.flag2=true;
        }else {
          this.flag2=false;
        }
      })
    },

    uploadPic(e) {
      let formData = new FormData();
      formData.append("file", e.target.files[0]);
      this.$axios({
        headers: {
          'Content-Type': "false",
        },
        method: 'post',
        url: "oss/upload",
        data: formData
      }).then(res => {
        if (res == 'fail') {
          alert("--对不起，添加失败--");
        } else {
          alert("--添加成功--");
          this.showImg = res.data;
          //截取文件名,赋给addUserForm.pic和editUserForm.pic
          this.addUserForm.pic = this.showImg.substring(this.showImg.lastIndexOf("/") + 1);
          this.editUserForm.pic = this.addUserForm.pic;
        }
      })
    },
    handleChange(value) {
      //此value是存储省市区三级代码的数组，同绑定值selectedOptions
      this.city = '';
      //获取city文本
      for (let c of value) {
        this.city += CodeToText[c];
      }
      //当点击提交修改按钮时，补全address
    },
    async removeUserById(id) {
      this.$confirm('此操作将永久删除该本用户, 是否继续?', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '不是',
        type: 'warning'
      }).then(() => {
        let url = '/user/delete/' + id;
        this.$axios.delete(url).then(res => {
          this.message(res);
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    changeLocked(id) {
      let url = "/user/changeLocked/" + id;
      this.$axios.post(url).then(res => {
        this.message(res);
      })
    },
    showEditDialog: function (row) {
      this.editUserForm = row;
      this.editDialogVisible = true;
      this.showImg = this.showImg + row.pic;
      //根据address解析省市区，和详细地址，反向获得代码，反显到修改对话框中
      //逐个字符扫描，判断字串是否对应code，对应则存入到绑定属性selectedOptions中，从下个字符开始扫描，直到扫描三次
      //先置空绑定数组
      this.selectedOptions = [];
      let start = 0;
      let end = 1;
      let t1;
      let t2;
      let tc;
      let t = 0;            //t表示得到的层数
      while (t < 3 & end < row.address.length) {
        if (t === 0) {
          tc = TextToCode[row.address.substring(start, end)];//第一层对象
        } else if (t === 1) {
          tc = TextToCode[t1][row.address.substring(start, end)];//第二层对象
        } else if (t === 2) {
          tc = TextToCode[t1][t2][row.address.substring(start, end)];//第三层对象
        }
        //若此对象非空，则获取其code，放入到绑定数组selectedOptions[]中
        if (tc != null) {
          t++;
          if (t === 1) {
            t1 = row.address.substring(start, end);
            this.selectedOptions.push(tc.code);
          } else if (t === 2) {
            t2 = row.address.substring(start, end);
            this.selectedOptions.push(tc.code);
          } else if (t === 3) {
            this.selectedOptions.push(tc.code);
          }
          //成功取值一次，从下个位置开始扫描
          start = end;
        }
        end++;
      }
      //此时start就是地址剩余部分的起始位置
      this.editUserForm.address = row.address.substring(start);
      console.log(this.selectedOptions)
    },
    editUserFormClose() {
      //清除修改对话框信息，但会丢失city
      this.$refs.editUserFormRef.resetFields();
      this.showImg = 'https://woniu-adopt.oss-cn-hangzhou.aliyuncs.com/adoptImages/'
      //多加载一次可以解决
      this.initUser();
      this.flag = true;

    },
    editUser() {
      let url = "/user/edit";

      //把绑定的code数组置空
      this.selectedOptions = [];
      this.$refs["editUserFormRef"].validate((valid) => {
        if (valid) {
          //完善address,只完善一次，还需在关闭修改对话框时重置flag
          if (this.flag) {
            this.editUserForm.address = this.city + this.editUserForm.address;
            this.flag = false;
          }
          this.$axios.post(url, this.editUserForm)
              .then(res => {
                this.message(res);
                this.editDialogVisible = false;
              })
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },
    //添加用户
    addUser() {
      let url = "/user/add";
      //完善address
      console.log(this.city)
      this.addUserForm.address = this.city + this.addUserForm.address;

      this.$refs.addUserFormRef.validate(validate => {
        if (validate) {
          this.$axios.post(url, this.addUserForm)
              .then(res => {
                this.message(res);
                this.addDialogVisible = false;
                //把绑定的code数组置空
                this.selectedOptions = [];
              })
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    //关闭增加用户的对话框
    addUserFormClose() {
      this.addDialogVisible = false;
      this.$refs.addUserFormRef.resetFields();
      this.showImg = 'https://woniu-adopt.oss-cn-hangzhou.aliyuncs.com/adoptImages/';
    },
    searchUser() {
      this.initUser();
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.pageNum = 1;
      this.initUser();
    },
    handleCurrentChange(newPage) {
      this.pageNum = newPage;
      this.initUser();
    },
    //初始化查询 用户信息
    initUser() {
      let url = "/user/list";
      this.$axios.get(url, {
        params: {
          now: this.pageNum,
          size: this.pageSize,
          name: this.username
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.userList = res.data.data.list;
          this.pageSize = res.data.data.pageSize;
          this.pageNum = res.data.data.pageNum;
          this.total = res.data.data.total;
        } else {
          this.error(res);
        }
      })
    },
    success(res) {
      this.$message({
        type: 'success',
        message: res.data.msg,
        duration: 1000
      });
      this.initUser();
    },
    error(res) {
      this.$message({
        type: 'error',
        message: res.data.msg,
        duration: 1000
      });
    },
    message(res) {
      if (res.data.code === 200) {
        this.$message({
          type: 'success',
          message: res.data.msg,
          duration: 1000
        });
        this.initUser();
      } else {
        this.$message({
          type: 'error',
          message: res.data.msg,
          duration: 1000
        })
      }
    }
  },
  created() {
    this.initUser();
  }
};
</script>
<style lang="less" scoped>
</style>
<!--存在bug：
1.修改对话框打开时，提交修改时正则验证不通过，会执行追加address，同时city会变空    2022-07-28

-->